package com.sunday.haowushop.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sunday.common.base.BaseFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.ptr.PtrClassicFrameLayout;
import com.sunday.common.widgets.ptr.PtrDefaultHandler;
import com.sunday.common.widgets.ptr.PtrFrameLayout;
import com.sunday.common.widgets.ptr.PtrHandler;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.haowushop.R;
import com.sunday.haowushop.adapter.GroupBuyOrderAdapter;
import com.sunday.haowushop.common.BaseApp;
import com.sunday.haowushop.entity.GroupBuyOrder;
import com.sunday.haowushop.http.ApiClient;
import com.sunday.haowushop.ui.WebViewActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/6/2.
 */

public class GroupBuyOrderListFragment extends BaseFragment {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.ptr_frame)
    PtrClassicFrameLayout ptrFrame;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;

    private Integer status;
    private long memberId;
    private int pageNo = 1, lastVisibleItem;

    private List<GroupBuyOrder> dataSet = new ArrayList<>();
    private GroupBuyOrderAdapter orderAdapter;
    private boolean isCanloadMore;
    private LinearLayoutManager layoutManager;

    public static GroupBuyOrderListFragment newInstance(int status) {
        GroupBuyOrderListFragment fragment = new GroupBuyOrderListFragment();
        Bundle args = new Bundle();
        args.putInt("status", status);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_order_list, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        memberId = BaseApp.getInstance().getMember().getId();
        if (getArguments() != null) {
            status = getArguments().getInt("status");
            if (status==0){status=null;}
        }
        orderAdapter = new GroupBuyOrderAdapter(mContext, dataSet);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(orderAdapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.horizontal_space_divider)
                .build());
        ptrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageNo = 1;
                getOrderList();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, recyclerView, header);
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == orderAdapter.getItemCount() && isCanloadMore) {
                    getOrderList();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

        orderAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final int p = (int) v.getTag();
                GroupBuyOrder item = dataSet.get(p);
                switch (v.getId()) {
                    case R.id.item_view:
                        //订单详情
                        intent=new Intent(mContext,GroupOrderDetailActivity.class);
                        intent.putExtra("groupOrder",item);
                        startActivity(intent);
                        break;
                    case R.id.order_btn1:
                        if (item.getStatus()==2){
                            confirmRecieve(p);
                        }else if (item.getStatus()==5){
                            intent=new Intent(mContext,GroupRefundDetailActivity.class);
                            intent.putExtra("order",item);
                            startActivity(intent);
                        }
                        break;
                    case R.id.order_btn2:
                        //查看物流
                        if (item.getStatus()==2){
                            intent = new Intent(mContext, WebViewActivity.class);
                            String url=String.format("https://m.kuaidi100.com/index_all.html?type=%1$s&postid=%2$s",item.getExpressEng(),item.getExpressNo());
                            intent.putExtra("url",url);
                            intent.putExtra("title", "物流查询");
                            startActivity(intent);
                        }
                    case R.id.order_btn3:
                        //申请退货
                        if (item.getStatus()==2){
                            intent=new Intent(mContext,GroupOrderApplyRefundActivity.class);
                            intent.putExtra("order",item);
                            startActivity(intent);
                        }
                        break;
                }
            }
        });
    }


    private void confirmRecieve(int p){
        showLoadingDialog(0);
        Call<ResultDO> call=ApiClient.getApiAdapter().confirmGroupRecieve(dataSet.get(p).getId());
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish){return;}
                dissMissDialog();
                if (response.body()==null){
                    return;
                }
                if (response.body().getCode()==0){
                    refresh();
                }else {
                    ToastUtils.showToast(mContext,response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext,R.string.network_error);
            }
        });
    }


    public void refresh() {
        pageNo = 1;
        getOrderList();
    }


    @Override
    public void onResume() {
        super.onResume();
        pageNo = 1;
        getOrderList();
    }

    private void getOrderList() {
        Call<ResultDO<List<GroupBuyOrder>>> call = ApiClient.getApiAdapter().getGroupOrderList(memberId,status,pageNo,Constants.PAGE_SIZE);
        call.enqueue(new Callback<ResultDO<List<GroupBuyOrder>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<GroupBuyOrder>>> call, Response<ResultDO<List<GroupBuyOrder>>> response) {
                if (isFinish) {
                    return;
                }
                ptrFrame.refreshComplete();
                ResultDO<List<GroupBuyOrder>> resultDO = response.body();
                if (resultDO != null) {
                    if (resultDO.getCode() == 0) {
                        if (pageNo == 1) {
                            dataSet.clear();
                        }
                        if (resultDO.getResult().size() ==  Constants.PAGE_SIZE) {
                            isCanloadMore = true;
                            pageNo++;
                        } else {
                            isCanloadMore = false;
                        }
                        dataSet.addAll(resultDO.getResult());
                        if (dataSet.size() == 0) {
                            emptyLayout.setErrorType(EmptyLayout.NODATA);
                            emptyLayout.setNoDataContent("暂无订单");
                        } else {
                            emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        }
                        orderAdapter.notifyDataSetChanged();
                    } else {
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                    }
                } else {
                    emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<GroupBuyOrder>>> call, Throwable t) {
                ptrFrame.refreshComplete();
                emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            }
        });
    }

}

